package com.permission.systempermission.comm.security;

import com.permission.systempermission.comm.constant.CheckResult;
import com.permission.systempermission.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    //需要跳过不拦截
    public static final String[] needskip = {"webjars","swagger","v2","login"};

    public static boolean containsString(String url) {
        if(url.equals("")){
            return true;
        }
        boolean flag = false;
        for (int i=0;i<needskip.length;i++){
            if(url.contains(needskip[i])){
                flag = true;
                break;
            }
            flag = false;
        }
        return  flag;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        String url = httpServletRequest.getRequestURI();
        if(containsString(url)){
            doFilter(httpServletRequest,httpServletResponse,filterChain);
            return;
        }
        String token = httpServletRequest.getHeader("token");
        // SecurityContextHolder每次接口请求都是为null，在token有效期内可以赋值
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            CheckResult checkResult = JwtUtils.validateJWT(token);
            System.out.println("toString():"+checkResult);
            if (checkResult.isSuccess()) {
                //续期认证
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=
                        new UsernamePasswordAuthenticationToken(checkResult.getClaims().getIssuer(),null,authorities);
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        doFilter(httpServletRequest,httpServletResponse,filterChain);
    }
}
